package cn.com.mall.search.service.impl;

import cn.com.mall.common.dto.es.SkuEsModel;
import cn.com.mall.search.constant.EsConstant;
import cn.com.mall.search.service.ProductSaveService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public void productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {

        BulkRequest request = new BulkRequest();
        for(SkuEsModel skuEsModel:skuEsModelList){
            IndexRequest indexRequest=new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String value = new ObjectMapper().writeValueAsString(skuEsModel);
            indexRequest.source(value, XContentType.JSON);
            request.add(indexRequest);
        }

        BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
        boolean b = bulk.hasFailures();
        if(!b){
            List<Object> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());

            log.error("商品上架成功：{}",collect);
        }

    }
}
